package com.my.rabbitmq.seven;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2023/11/30 15:23
 */

import com.my.utils.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  死信队列 实战
 *  消费者1
 */
public class Consumer01 {
    
    // 普通交换机的名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    // 死信交换机的名称
    public static final String DEAD_EXCHANGE = "dead_exchange";
    // 普通队列的名称
    public static final String NORMAL_QUEUE = "normal_queue";
    // 死信队列的名称
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception{
        Channel channel = RabbitMQUtils.getChannel();
        // 声明普通交换机和死信交换机 类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        
        // 声明普通队列
        Map<String, Object> arguments = new HashMap<>();
        // 过期时间 单位 ms
        //arguments.put("x-message-ttl", 100000);
        // 正常队列设置死信交换机 转发消息到死信队列
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 设置死信routingKey
        arguments.put("x-dead-letter-routing-key", "lisi");
        // 设置队列最大长度
        arguments.put("x-max-length", 6);
        
        channel.queueDeclare(NORMAL_QUEUE, false, false,false, arguments);
        
        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        
        // 绑定交换机与队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");
            if ("info5".equals(msg)){
                System.out.println(msg + "被Consumer01拒绝接收了");
                // requeue：是否塞回原队列
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            }else {
                System.out.println("Consumer01接收的消息：" + msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
            
        };
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println(consumerTag + "接收消息失败");
        };
        
        // 开启手动应答
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, cancelCallback);
        
        
    }
    
}
